import { createRouter, createWebHistory } from 'vue-router'
import { FormatToken, SettingUserRouter, Vaild } from '../tools/index'
import store from '../store/index'
import { ElMessage } from "element-plus"
const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            name: "login",
            path: "/login",
            component: () => import("../views/index/Login.vue")
        }, {
            name: "notfound",
            path: "/:pathMatch(.*)", //正则表达式匹配(不在路由里的都走这个)
            component: () => import("../views/index/NotFound.vue")
        }, {
            name: "admin",
            path: "/", //首页
            component: () => import("../views/index/Root.vue"),
            children: [
                // {
                //     name: "测试页面",
                //     path: "/test",
                //     component: () => import("../views/index/Test.vue")
                // },{
                //     name: "工作台",
                //     path: "/",
                //     component: () => import("../views/index/DeskTop.vue")
                // }, {
                //     name: "个人信息",
                //     path: "/person",
                //     component: () => import("../views/index/Person.vue")
                // }
            ]
        }
    ]
})

//路由导航：到某个页面之前的拦截 to:去哪里 from从哪里来，next下一个
router.beforeEach(async (to, from, next) => {
    console.log(from.name);
    if (to.path.toLowerCase() != "/login") {
        //读取数据并设置动态路由
        await SettingUserRouter()
    }
    if (store().token == "" || !store().token) {
        if (to.path.toLowerCase() != "/login") {
            next("/login")
        }
    } else {
        // Todo：判断登录有效期
        const exp = FormatToken(store().token)?.exp as number
        if (!Vaild(exp) && to.path.toLowerCase() != "/login") {
            ElMessage.error("登录已过期，请重新登录");
            next("/login")
        }
    }
    //由于是动态添加的路由需要在下次导航才生效
    if (to.name == "notfound") {
        //所以需要手动跳转到动态添加的路由，前提是跳转的path需要在路由中存在才行
        if (router.getRoutes().find(f => f.path.toLowerCase() == to.path.toLowerCase())) {
            next(to.path)
        }
    }
    next()
})

export default router